package com.hyk.learning.common.utils;

import com.sun.org.apache.bcel.internal.generic.FADD;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @className: AdaptiveMetrics
 * @author: hyk199710
 * @description: TODO
 * @date: 2024/8/19 22:41
 */
public class AdaptiveMetrics {

    private final ConcurrentHashMap<String, AdaptiveMetrics> metricsStatistics = new ConcurrentHashMap<>();
    //服务提供者响应时间
    private long currentProviderTime = 0;
    private double providerCPULoad = 0;
    private long lastLatency = 0;
    //服务消费者者调用时间
    private long currentTime = 0;

    private long pickTime = System.currentTimeMillis();

    private double beta = 0.5;
    private final AtomicLong consumerReq = new AtomicLong();
    private final AtomicLong consumerSuccess = new AtomicLong();
    private final AtomicLong errorReq = new AtomicLong();

    private double ewma = 0;

    public AdaptiveMetrics getStatus(String serviceUrl){
        return metricsStatistics.computeIfAbsent(serviceUrl, k -> new AdaptiveMetrics());
    }

    public void addConsumerReq(String serviceUrl){
        AdaptiveMetrics metrics = getStatus(serviceUrl);
        metrics.consumerReq.incrementAndGet();
    }

    public void addConsumerSuccess(String serviceUrl){
        AdaptiveMetrics metrics = getStatus(serviceUrl);
        metrics.consumerSuccess.incrementAndGet();
    }

    public void addErrorReq(String serviceUrl){
        AdaptiveMetrics metrics = getStatus(serviceUrl);
        metrics.errorReq.incrementAndGet();
    }

    public void setPickTime(String serviceUrl, long time){
        AdaptiveMetrics metrics = getStatus(serviceUrl);
        metrics.pickTime = time;
    }

    public void setProviderMetrics(String serviceUrl, Map<String, String> metricsMap){
        AdaptiveMetrics metrics = getStatus(serviceUrl);

        long serviceTime = Long.parseLong(Optional.ofNullable(metricsMap.get("curTime"))
                .filter(v -> StringUtil.isNumeric(v, false))
                .orElse("0"));
        if(metrics.currentProviderTime > serviceTime){
            return;
        }

        metrics.currentProviderTime = serviceTime;
        metrics.currentTime = serviceTime;
        metrics.providerCPULoad = Double.parseDouble(Optional.ofNullable(metricsMap.get("load"))
                .filter(v -> StringUtil.isNumeric(v, false))
                .orElse("0"));
        metrics.lastLatency = Long.parseLong((Optional.ofNullable(metricsMap.get("rt"))
                .filter(v -> StringUtil.isNumeric(v, false))
                .orElse("0")));

        metrics.beta = 0.5;
        metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
    }

    public double getLoad(String serviceUrl, int weight, int timeout){
        AdaptiveMetrics metrics = getStatus(serviceUrl);

        if(System.currentTimeMillis() - metrics.pickTime > timeout * 2){
            return 0;
        }

        if (metrics.currentTime > 0) {
            long multiple = (System.currentTimeMillis() - metrics.currentTime) / timeout + 1;
            if (multiple > 0) {
                if (metrics.currentProviderTime == metrics.currentTime) {
                    // penalty value
                    metrics.lastLatency = timeout * 2L;
                } else {
                    metrics.lastLatency = metrics.lastLatency >> multiple;
                }
                metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
                metrics.currentTime = System.currentTimeMillis();
            }
        }

        long inflight = metrics.consumerReq.get() - metrics.consumerSuccess.get() - metrics.errorReq.get();
        return metrics.providerCPULoad
                * (Math.sqrt(metrics.ewma) + 1)
                * (inflight + 1)
                / ((((double) metrics.consumerSuccess.get() / (double) (metrics.consumerReq.get() + 1)) * weight) + 1);
    }
}
